package net.takela.common.security.handler;

import net.takela.common.security.model.AuthUser;
import net.takela.common.security.model.UserAuthToken;
import net.takela.common.security.service.AuthTokenManager;
import net.takela.common.security.service.UserAuthTokenService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;


public class AuthSuccessHandler implements AuthenticationSuccessHandler {
    private AuthTokenManager authTokenManager;
    private UserAuthTokenService userAuthTokenService;
    /**
     * 
     */
    public AuthSuccessHandler(AuthTokenManager authTokenManager, UserAuthTokenService userAuthTokenService){
        this.authTokenManager = authTokenManager;
        this.userAuthTokenService = userAuthTokenService;
    }
    
    /**
     * 
     */
    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        System.out.println("=== AuthSuccessHandler:"+authentication);
        AuthUser user = (AuthUser) authentication.getPrincipal();
        String jti = String.valueOf(UUID.randomUUID().toString());
        String jwts = authTokenManager.createJwtToken(String.valueOf(user.getUid()), user);
        userAuthTokenService.removeToken(user.getUid());

//        UserAuthToken userAuthToken = authTokenManager.createAuthToken(user.getUid(), jti, jwts);
//        userAuthTokenService.addToken(userAuthToken);
//        HttpResponse r = new HttpResponse(0, "OK");
//        r.setData(jwts);
//        new ObjectMapper().writeValue(response.getWriter(), r);
    }
    private UserAuthToken createAuthToken(Long uid, String jwts){
        String jti = String.valueOf(UUID.randomUUID().toString());
        UserAuthToken newToken = new UserAuthToken();
        newToken.setUid(uid);
        newToken.setClientId(jti);
        newToken.setToken(DigestUtils.sha256Hex(jwts));
        newToken.setUpdateTime(new Date());
        return newToken;
    }
}
